import com.swetake.util.Qrcode;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;

/**生成二维码
 * Created by ${chengwengao} on 2017/1/22.
 * * 注：qrcode创建和读取二维码的jar在同不同的两个文件中，路径在qrcode文件夹下，记得导入
 */
public class CreateQRCode {
    public static void main(String[] args) throws Exception{
        Qrcode x = new Qrcode();
        x.setQrcodeErrorCorrect('M');   //纠错等级
        x.setQrcodeEncodeMode('B'); //N代表数字，A代表a-z,B代表其他
        x.setQrcodeVersion(7);
        String qrData = "TiDB is a distributed NewSQL database compatible with MySQL protocol";
        int width = 67 + 12*(7-1);  //7是版本号，公式，二维码图片将填满，不留空白
        int height = 67 + 12*(7-1);
        BufferedImage bufferedImage = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);

        Graphics2D gs = bufferedImage.createGraphics();
        gs.setBackground(Color.white);
        gs.setColor(Color.black);
        gs.clearRect(0,0,width,height);

        int pixoff = 2; //偏移量，防止解析出错

        byte[] d = qrData.getBytes("gb2312");
        if(d.length>0 && d.length<120){
            boolean[][] s = x.calQrcode(d);
            for(int i=0;i<s.length;i++){
                for (int j=0;j<s.length;j++){
                    if (s[j][i]){
                        gs.fillRect(j * 3 + pixoff, i * 3 + pixoff, 3, 3);
                    }
                }
            }
        }
        gs.dispose();
        bufferedImage.flush();
        ImageIO.write(bufferedImage,"png",new File("D:/qrcode.png"));
        System.out.println("二维码生成成功!");
    }
}
